<template>
  <div class="tools">
    <el-input v-model="formData.displayName" placeholder="请输入"></el-input>
    &emsp;
    <el-input-number v-model="scale" :step="0.1" style="width: 200px"></el-input-number>
    &emsp;
    <el-button @click="submit">保存</el-button>
  </div>
  <div ref="view" class="view element no-select"
       @mousedown="ready"
       @mousemove="move"
       @mouseup="over">
    <section ref="content" :style="{'scale': scale}" class="content">
      <Tag :form-item="workflow"></Tag>
    </section>
  </div>
</template>

<script lang="ts" setup>
import Tag from "./Tag.vue";
import { onMounted, ref } from "vue";
import { v4 as uuidv4 } from "uuid";
import { useEventBus } from "@/hooks/event/useEventBus";
import { getWorkflowDetails, saveWorkFlow } from "@/api/WorkFlow";
import { useRoute } from "vue-router";
import loadsh from "loadsh";

const route = useRoute();
const bus = useEventBus();
const scale = ref(1);
const workflow = ref(
  {
    displayName: "开始",
    type: "Workflow",
    activityId: uuidv4()
  }
);
const formData = ref({});
const down = ref<boolean>(false);
const view = ref();
const content = ref();

const ready = (event) => {
  down.value = true;
};
const over = (event) => {
  down.value = false;
};
let lastX: any = null; // 用于存储上一次鼠标的X坐标
let lastY: any = null; // 用于存储上一次鼠标的X坐标

const move = (e: any) => {
  e.preventDefault();
  if (down.value) {
    if (lastX !== null) {
      if (e.clientX > lastX) {
        view.value.scrollTo({
          left: view.value.scrollLeft - 10
        });
        //'鼠标向右移动'
      } else if (e.clientX < lastX) {
        view.value.scrollTo({
          left: view.value.scrollLeft + 10
        });
        //'鼠标向左移动'
      }
    }
    if (lastY !== null) {
      if (e.clientY > lastY) {
        view.value.scrollTo({
          top: view.value.scrollTop - 10
        });
        //'鼠标向右移动'
      } else if (e.clientY < lastY) {
        view.value.scrollTo({
          top: view.value.scrollTop + 10
        });
        //'鼠标向左移动'
      }
    }
    lastX = e.clientX; // 更新上一个X坐标
    lastY = e.clientY; // 更新上一个X坐标
  }
};


onMounted(
  () => {
    view.value.scrollTo({
      left: content.value.clientWidth / 2 - view.value.clientWidth / 2,
      top: content.value.clientHeight / 2 - view.value.clientHeight / 2
    });
    bus.on("Add", (newTree: any) => {
      addTag(workflow.value, newTree);
    });
    bus.on("del", (activityId: string) => {
      delTree(workflow.value, activityId);
    });
  }
);

const getOutcome = (newTree) => {
  if (newTree.type == "TaskApproveActivity" || newTree.type == "AuditActivity") {
    return "yesNext";
  } else {
    return "next";
  }
};

const addTag = (tree, newTree) => {
  const outcome = getOutcome(newTree);
  if (!newTree) return;
  if (tree.activityId == newTree.sourceActivityId) {
    if(tree.type != "AuditActivity" && tree.type != "TaskApproveActivity") {
      tree.targetActivityId = newTree.activityId;
    }
    if (newTree.outcome == "Done") {
      if (tree.next) {
        if (newTree.type == "TaskApproveActivity" || newTree.type == "AuditActivity") {
          tree.next.outcome = "同意";
        } else {
          tree.next.outcome = "Done";
        }
        newTree[outcome] = tree.next;
        tree.next = newTree;
        newTree[outcome].sourceActivityId = newTree.activityId;
        if(newTree.type != "AuditActivity" && newTree.type != "TaskApproveActivity") {
          newTree.targetActivityId = newTree[outcome].activityId;
        }
      } else {
        tree.next = newTree;
      }
    } else if (newTree.outcome == "同意") {
      if (tree.yesNext) {
        if (newTree.type == "TaskApproveActivity" || newTree.type == "AuditActivity") {
          tree.yesNext.outcome = "同意";
        } else {
          tree.next.outcome = "Done";
        }
        newTree[outcome] = tree.yesNext;
        tree.yesNext = newTree;
        newTree[outcome].sourceActivityId = newTree.activityId;
        if(newTree.type != "AuditActivity" && newTree.type != "TaskApproveActivity") {
          newTree.targetActivityId = newTree[outcome].activityId;
        }
      } else {
        tree.yesNext = newTree;
      }
    } else if (newTree.outcome == "拒绝") {
      if (tree.noNext) {
        newTree[outcome] = tree.noNext;
        tree.noNext = newTree;
        newTree[outcome].sourceActivityId = newTree.activityId;
        if(newTree.type != "AuditActivity" && newTree.type != "TaskApproveActivity") {
          newTree.targetActivityId = newTree[outcome].activityId;
        }
      } else {
        tree.noNext = newTree;
      }
    }
  } else {
    if (tree.next) {
      addTag(tree.next, newTree);
    }
    if (tree.yesNext) {
      addTag(tree.yesNext, newTree);
    }
    if (tree.noNext) {
      addTag(tree.noNext, newTree);
    }
  }
};

function del(tree: any, sourceActivityId: string, outcome: string, type: string) {
  if (!tree) return;
  let key;
  if (outcome == "Done") {
    key = "next";
  } else if (outcome == "同意") {
    key = "yesNext";
  } else if (outcome == "拒绝") {
    key = "noNext";
  } else {
    key = "Done";
  }
  if (tree.activityId == sourceActivityId) {
    if (type == "TaskApproveActivity" || type == "AuditActivity") {
      tree[key] = null;
    } else {
      tree[key] = loadsh.cloneDeep(tree[key]?.next);
    }
  } else {
    if (tree.next) {
      del(tree.next, sourceActivityId, outcome, type);
    }
    if (tree.yesNext) {
      del(tree.yesNext, sourceActivityId, outcome, type);
    }
    if (tree.noNext) {
      del(tree.noNext, sourceActivityId, outcome, type);
    }
  }
}

function delTree(tree: any, activityId: string) {
  if (!tree) {
    return false;
  }
  if (tree.activityId == activityId) {
    if (tree.sourceActivityId || tree.activityId) {
      del(workflow.value, tree.sourceActivityId, tree.outcome, tree.type);
    }
  } else {
    if (tree.next) {
      delTree(tree.next, activityId);
    }
    if (tree.yesNext) {
      delTree(tree.yesNext, activityId);
    }
    if (tree.noNext) {
      delTree(tree.noNext, activityId);
    }
  }
}

const Tree_to_activities = (tree: any) => {
  if (!tree) return;
  if (tree.activityId) {
    activities.value.push(tree);
    if (tree.next) {
      Tree_to_activities(tree.next);
    }
    if (tree.yesNext) {
      Tree_to_activities(tree.yesNext);
    }
    if (tree.noNext) {
      Tree_to_activities(tree.noNext);
    }
  }
}
const Tree_to_connections = () => {
  const cons = activities.value.filter(_ => _.sourceActivityId);
  cons.forEach(con => {
    connections.value.push({
      outcome: con.outcome,
      sourceActivityId: con.sourceActivityId,
      targetActivityId: con.activityId
    });
  });
};
const submit = async () => {
  activities.value = [];
  connections.value = [];
  Tree_to_activities(workflow.value);
  Tree_to_connections();
  console.log(activities.value);
  console.log(connections.value);
  console.log(workflow.value)
  const res = await saveWorkFlow({
    ...formData.value,
    workflowDefinitionId: route.query.id,
    persistenceBehavior: "WorkflowBurst",
    activities: activities.value,
    connections: connections.value,
    isLatest: true,
    isPublished: false,
    isSingleton: false
  });
  if (res.status == 200) {
    init();
  }
};

const activities = ref<any[]>([]);
const connections = ref<any[]>([]);


const isData = (data: any) => {
  if (Array.isArray(data)) {
    return JSON.stringify(data);
  }
  if (!data) {
    return JSON.stringify([]);
  }
};

const init = async () => {
  //查询workflow详情
  const res = await getWorkflowDetails(route.query.id);
  if (res.status == 200) {
    formData.value = res.data;
    activities.value = res.data.activities;
    console.log(activities.value)
    connections.value = res.data.connections.filter(_ => _.sourceActivityId != _.targetActivityId);
    connections.value.forEach((item: any) => {
      activities.value.forEach(_ => {
        if (_.activityId == item.sourceActivityId) {
          if (_.type != "TaskApproveActivity" && _.type != "AuditActivity") {
            console.log(_.type)
            _.targetActivityId = item.targetActivityId;
          }
        }
        if (_.activityId == item.targetActivityId) {
          _.sourceActivityId = item.sourceActivityId;
          _.outcome = item.outcome;
        }
      });
    });
    console.log(activities.value)
    if(activities.value.length){
      const root = activities.value.find(_ => !_.sourceActivityId);
      assembleTree(root);
      workflow.value = root;
    }
    console.log(workflow.value);
  }
};

const assembleTree = (tree) => {
  if (!tree) return;
    if(tree.type != "TaskApproveActivity" && tree.type != "AuditActivity") {
      const son = activities.value.find((item: any) => item.activityId == tree?.targetActivityId);
      tree.next = son
      if(son && son.outcome == "Done"){
        assembleTree(tree.next);
      }
    }else{
      const sons = activities.value.filter((item: any) => item.sourceActivityId == tree?.activityId);
      sons.forEach(son => {
        if (son.outcome == "同意") {
          tree.yesNext = son;
          assembleTree(tree.yesNext);
        } else if (son.outcome == "拒绝") {
          tree.noNext = son;
          assembleTree(tree.noNext);
        }
      })
    }
};

init();
</script>

<style lang="less" scoped>
.view {
  border: 1px #ccc solid;
  width: 100%;
  height: 98vh;
  overflow: auto;
}

.content {
  width: 3000px;
  height: 3000px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  cursor: grab;

  &:active {
    cursor: grabbing;
  }
}


.tools {
  z-index: 99;
  position: absolute;
  right: 10px;
  top: 10px;
  display: flex;
  align-items: center;
}
</style>
